use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use sqlx::{Error, FromRow, Pool, Postgres};
use uuid::Uuid;
use void_log::log_info;

#[derive(Debug, Clone, Serialize, Deserialize, FromRow, Default)]
pub struct SysGuild {
    pub id: Option<Uuid>,
    pub name: Option<String>,
    pub avatar: Option<String>,
    pub status: Option<i16>,
    pub create_time: Option<NaiveDateTime>,
    pub update_time: Option<NaiveDateTime>,
}

impl SysGuild {
    pub async fn _select_all(pool: &Pool<Postgres>) -> Vec<Self> {
        let sql = "SELECT * FROM sys_guild";
        sqlx::query_as::<_, Self>(sql).fetch_all(pool).await.unwrap()
    }

    pub async fn _select_name(pool: &Pool<Postgres>, name: &str) -> Self {
        let sql = "SELECT * FROM sys_guild where name = ?";
        sqlx::query_as::<_, Self>(sql).bind(name).fetch_one(pool).await.unwrap()
    }

    pub async fn _select_user_name(pool: &Pool<Postgres>, user_name: &str) -> Result<Vec<Self>, Error> {
        log_info!("查询 Name: {user_name}所加群组");
        let sql = "SELECT a.* FROM sys_user a, sys_user_guild b, sys_guild c where a.id = b.user_id and b.guild_id = c.id and a.name = $1";
        sqlx::query_as::<_, Self>(sql).bind(user_name).fetch_all(pool).await
    }

    pub async fn select_user_token(pool: &Pool<Postgres>, user_token: &str) -> Result<Vec<Self>, Error> {
        log_info!("查询 Token: {user_token}所加群组");
        let sql = "SELECT c.* FROM sys_user a, sys_user_guild b, sys_guild c where a.id = b.user_id and b.guild_id = c.id and a.token = $1";
        sqlx::query_as::<_, Self>(sql).bind(user_token).fetch_all(pool).await
    }
}